package com.zengqingfa.examples.mybatisplus.response;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.UUID;

@Slf4j
@Data
public final class Result<T> implements Serializable {
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private Result() {
    }

    private Result(Status status, T data, String message) {
        this.id = UUID.randomUUID().toString().replaceAll("-", "");
        this.status = status;
        this.data = data;
        this.traceId = TraceContext.traceId();
        this.message = message;
    }

    public static <T> Result<T> success(T data) {
        return new Result(Status.Success, data, "");
    }

    public static <T> Result<T> fail(String message) {
        return new Result(Status.Fail, "", message);
    }

    public static <T> Result<T> unLogin() {
        return new Result(Status.unLogin, "", "用户未登录");
    }

    private String id;
    /**
     * 数据内容
     **/
    private T data;
    /**
     * 调用接口状态
     **/
    private Status status;
    /**
     * 消息,如错误消息
     ***/
    private String message;
    /**
     * 接口调用花费时间（单位:秒）
     **/
    private BigDecimal cost;
    /*** 接口响应时间 ***/
    private String time;

    /**
     * 链路追踪id
     **/
    private String traceId;


    @Override
    public String toString() {
        try {
            return JSON.toJSONString(this);
        } catch (Exception e) {
            log.error(e.getMessage(), e, this.getClass());
            return JSON.toJSONString(Result.fail("数据处理异常"));
        }
    }

    enum Status {
        Success, Fail, unLogin
    }
}